/**
 * 
 */
package com.swfee.qinben.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.database.Cursor;

import com.swfee.qinben.dao.DatabaseHelper;
import com.swfee.qinben.model.LastLogin;
import com.swfee.qinben.util.PasswordUtils;

/**
 * @author ddr
 * 
 */
public class LastLoginService extends DbBaseService<LastLogin> {

	public LastLoginService(Context ctx) {
		super(ctx);
	}

	public final static String[] CLOUMNS = { "login_name", "login_pwd",
			"app_code","login_date" };
	public final static String TABLE_NAME = DatabaseHelper.T_LASTLOGIN;

	

	public LastLogin getLastLogin() {
		List<LastLogin> list = findByProps(null, "login_date DESC");
		return list.isEmpty() ? null : list.get(0);
	}

	public boolean removeLastLogin(String loginName) {
		int i = deleteById(loginName);
		return i >= 1;
	}

	public long updateLastLogin(LastLogin loginInfo) {
		return updateById(loginInfo.toCloumnCotentValues(),
				loginInfo.getLoginName());
	}

	public LastLogin cursorToModel(Cursor cu) {

		LastLogin ll = new LastLogin();
		int i = 0;
		ll.setLoginName(cu.getString(i++));
		ll.setPassword(PasswordUtils.base64DoubleToPass(cu.getString(i++)));
		ll.setAppCode(cu.getString(i++));
		ll.setLoginDate(new Date(cu.getLong(i++)));
		return ll;
	}

	public List<LastLogin> cursorToModels(Cursor cu) {
		List<LastLogin> list = new ArrayList<LastLogin>();
		while (cu.moveToNext()) {
			list.add(cursorToModel(cu));
		}
		return list;
	}
	
	public void deleteLastLogin() {
		deleteAll();
	}

	public void saveLastLogin(LastLogin t) {
		LastLogin ll = getLastLogin();
		t.setLoginDate(new Date());
		if (ll != null) {
			updateById(t.toCloumnCotentValues(), t.getLoginName());
		} else {
			insert(t);
		}
	}

	@Override
	public String[] getClounms() {
		return CLOUMNS;
	}

	@Override
	public String getTableName() {
		return TABLE_NAME;
	}

	@Override
	public long insert(LastLogin t) {
		t.setLoginDate(new Date());
		return super.insert(t);
	}
	
	public long saveOrUpdateLastLogin(LastLogin t){
		Object o =  findById(t.getLoginName());
		if(o!=null){
			return  updateById(t.toCloumnCotentValues(), t.getLoginName());
		}else{
			return insert(t);
		}
	}

}
